package desp.test.inner.demo;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;

/**
 * 生成公私钥对
 * @author wuwenzhe
 *
 */
public class GenerateKeyPair {

	public static void main(String[] args) {
		try {
			SecureRandom sr = new SecureRandom();
			KeyPairGenerator kg = KeyPairGenerator.getInstance("RSA",
					new org.bouncycastle.jce.provider.BouncyCastleProvider());
			// 注意密钥大小1024
			kg.initialize(1024, sr);
			KeyPair keyPair = kg.generateKeyPair();
			PrivateKey priKey = keyPair.getPrivate();
			PublicKey pubKey = keyPair.getPublic();
			byte[] publicKey = pubKey.getEncoded();
			byte[] privateKey = priKey.getEncoded();
			System.out.println("公钥：" + pubKey.getFormat() + " ; "
					+ byteArr2HexString(publicKey));
			System.out.println("私钥：" + priKey.getFormat() + " ; "
					+ byteArr2HexString(privateKey));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	public static String byteArr2HexString(byte[] bytearr) {
		if (bytearr == null) {
		return "null";
		}
		StringBuffer sb = new StringBuffer();
		for (int k = 0; k < bytearr.length; k++) {
		if ((bytearr[k] & 0xFF) < 16) {
		sb.append("0");
		}
		sb.append(Integer.toString(bytearr[k] & 0xFF, 16));
		}
		return sb.toString();
		}

}
